package com.zhouwr.protocol;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zhouwr.common.enums.ProtocolType;
import com.zhouwr.common.message.DeviceHeartMessage;
import com.zhouwr.common.message.DeviceMessage;
import com.zhouwr.common.message.Message;
import com.zhouwr.common.network.DeviceMessageCodec;
import com.zhouwr.common.network.TcpConnectContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nonnull;
import java.io.Serializable;

/**
 * The type Wireless 120 codec.
 *
 * @program: forallcn -iotps
 * @description: WIRELESS120的编解码器
 * @author: zhouwr
 * @create: 2020 -12-05 13:47
 * @version：1.0
 */
@Slf4j
@ChannelHandler.Sharable
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})
public class Wireless120Codec implements DeviceMessageCodec<TcpConnectContext>, Serializable {
    private static final long serialVersionUID = 1L;

    @Override
    public ProtocolType getProtocolType() {
        return ProtocolType.TCP;
    }

    @Nonnull
    @Override
    public DeviceMessage decode(TcpConnectContext connectContext, @Nonnull Object o) {
        ByteBuf byteBuf = (ByteBuf) o;

        log.info("编码器接收到数据：{}", byteBuf);

        byte[] bytes = ByteBufUtil.getBytes(byteBuf);

        // TODO 增加设备认证，目前只要连接上，根据连接IP地址判断成功后即为合法接入设备 2022/03/20 zhouwenrong

        /* 心跳 */
        // TODO 心跳标志放在设备功能管理，这里先写死。2022/03/20 zhouwenrong
        if ("heart".equals(new String(bytes))) {
            log.info("心跳");
            DeviceHeartMessage heartMessage = new DeviceHeartMessage("heart", String.class);
            heartMessage.setDeviceId(connectContext.getDeviceId());
            heartMessage.setDeviceName(connectContext.getDeviceName());
            return heartMessage;
        }

        StringBuilder dump = new StringBuilder("\n");
        ByteBufUtil.appendPrettyHexDump(dump, byteBuf);
        log.info("{}", dump);
//        networkConnectContext
        return (DeviceMessage)o;
    }

    @Nonnull
    @Override
    public Message encode(TcpConnectContext connectContext, @Nonnull Object o) {
        return (Message)o;
    }
}
